import gradio as gr
import requests
import json
from fastapi.testclient import TestClient
from app import app


# API endpoint
API_URL = "/text_predict"
client = TestClient(app)

def analyze_sentiment(text):
    """Send text to API and get sentiment analysis results"""
    if not text.strip():
        return "请输入文本", "<div>无可视化内容</div>"
    
    # Send request to FastAPI
    response = client.post(
        API_URL,
        json={"text": text}
    )

    
    if response.status_code == 200:
        result = response.json()
        sentiment = result.get("predicted_class", "未知")
        vis_data = result.get("vis_data", "<div>无可视化内容</div>")
                                
        return sentiment, vis_data
    else:
        return f"API错误: {response.status_code}", "<div>分析失败</div>"

# Create the Gradio interface
with gr.Blocks() as demo:
    gr.Markdown("# 文本情感分析")
    
    with gr.Row():
        with gr.Column(scale=4):
            text_input = gr.Textbox(
                label="输入文本",
                placeholder="请输入需要分析情感的文本...",
                lines=5
            )
        with gr.Column(scale=1, min_width=100):
            submit_btn = gr.Button("分析", variant="primary")
    
    with gr.Row():
        with gr.Column(scale=1):
            sentiment_output = gr.Textbox(label="情感分析结果")
        with gr.Column(scale=3):
            attention_viz = gr.HTML(label="注意力可视化")
    
    submit_btn.click(
        fn=analyze_sentiment,
        inputs=text_input,
        outputs=[sentiment_output, attention_viz]
    )
    
    gr.Examples(
        examples=[
            "三里屯modo，吃西班牙大餐????，增加快?，?自己打?，最重要是和大美妞@NicoleZeng  ?度六一！（PS：?迫美女吃晚餐，你完全不需要?肥）[耶][耶][爱你]",
            "每天早上起床你有两个选择要么趴着继续睡去做你没有做完的美梦要么拉开被子去完成你没有完成的梦想",
            "我以为~~~[泪]//@特工傀儡梅姐夫: [泪]//@马其顿鸭梨山大大帝: 感同身受//@口木我鸟:感同身受[泪]"
        ],
        inputs=text_input,
    )

if __name__ == "__main__":
    demo.launch()
